package com.ruoyi.common.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Word文档解析工具类
 * 
 * @author lzk
 * @date 2025-01-27
 */
@Component
public class WordDocumentUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(WordDocumentUtil.class);
    
    /**
     * 解析Word文档
     * 
     * @param file 上传的Word文档
     * @return 解析结果，包含标题和内容
     */
    public WordParseResult parseWordDocument(MultipartFile file) {
        WordParseResult result = new WordParseResult();
        
        try (InputStream inputStream = file.getInputStream()) {
            String fileName = file.getOriginalFilename();
            
            if (fileName != null && fileName.toLowerCase().endsWith(".docx")) {
                // 解析 .docx 文件
                return parseDocxFile(inputStream);
            } else if (fileName != null && fileName.toLowerCase().endsWith(".doc")) {
                // 解析 .doc 文件
                return parseDocFile(inputStream);
            } else {
                result.setSuccess(false);
                result.setMessage("不支持的文件格式，请上传 .doc 或 .docx 文件");
                return result;
            }
        } catch (Exception e) {
            logger.error("解析Word文档失败", e);
            result.setSuccess(false);
            result.setMessage("解析Word文档失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 解析 .docx 文件
     */
    private WordParseResult parseDocxFile(InputStream inputStream) throws IOException {
        WordParseResult result = new WordParseResult();
        
        try (XWPFDocument document = new XWPFDocument(inputStream)) {
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            
            if (paragraphs.isEmpty()) {
                result.setSuccess(false);
                result.setMessage("文档内容为空");
                return result;
            }
            
            // 提取标题（第一个段落作为标题）
            String title = paragraphs.get(0).getText().trim();
            if (title.isEmpty()) {
                title = "无标题文档";
            }
            result.setTitle(title);
            
            // 提取内容（从第二个段落开始）
            StringBuilder content = new StringBuilder();
            for (int i = 1; i < paragraphs.size(); i++) {
                String paragraphText = paragraphs.get(i).getText().trim();
                if (!paragraphText.isEmpty()) {
                    content.append(paragraphText).append("\n\n");
                }
            }
            
            String contentText = content.toString().trim();
            if (contentText.isEmpty()) {
                contentText = "文档内容为空";
            }
            result.setContent(contentText);
            result.setSuccess(true);
            result.setMessage("解析成功");
            
        } catch (Exception e) {
            logger.error("解析 .docx 文件失败", e);
            result.setSuccess(false);
            result.setMessage("解析 .docx 文件失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 解析 .doc 文件
     */
    private WordParseResult parseDocFile(InputStream inputStream) throws IOException {
        WordParseResult result = new WordParseResult();
        
        try (HWPFDocument document = new HWPFDocument(inputStream)) {
            WordExtractor extractor = new WordExtractor(document);
            String[] paragraphs = extractor.getParagraphText();
            
            if (paragraphs.length == 0) {
                result.setSuccess(false);
                result.setMessage("文档内容为空");
                return result;
            }
            
            // 提取标题（第一个段落作为标题）
            String title = paragraphs[0].trim();
            if (title.isEmpty()) {
                title = "无标题文档";
            }
            result.setTitle(title);
            
            // 提取内容（从第二个段落开始）
            StringBuilder content = new StringBuilder();
            for (int i = 1; i < paragraphs.length; i++) {
                String paragraphText = paragraphs[i].trim();
                if (!paragraphText.isEmpty()) {
                    content.append(paragraphText).append("\n\n");
                }
            }
            
            String contentText = content.toString().trim();
            if (contentText.isEmpty()) {
                contentText = "文档内容为空";
            }
            result.setContent(contentText);
            result.setSuccess(true);
            result.setMessage("解析成功");
            
        } catch (Exception e) {
            logger.error("解析 .doc 文件失败", e);
            result.setSuccess(false);
            result.setMessage("解析 .doc 文件失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * Word文档解析结果
     */
    public static class WordParseResult {
        private boolean success;
        private String message;
        private String title;
        private String content;
        
        public boolean isSuccess() {
            return success;
        }
        
        public void setSuccess(boolean success) {
            this.success = success;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
        
        public String getTitle() {
            return title;
        }
        
        public void setTitle(String title) {
            this.title = title;
        }
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
    }
} 